package org.mklink.util;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 全局线程池工具类，支持动态调整线程池大小
 *
 * @author WangYixiong
 */
public class GlobalThreadPool {
    // 创建一个可动态调整的线程池
    private static ThreadPoolExecutor THREAD_POOL;
    
    /**
     * 构造函数，初始化指定核心线程数的线程池
     * @param threadCount 核心线程数
     */
    public GlobalThreadPool(int threadCount) {
        THREAD_POOL = new ThreadPoolExecutor(
                threadCount
                , threadCount
                , 30L
                , TimeUnit.MILLISECONDS
                ,new LinkedBlockingDeque<>()
                , Executors.defaultThreadFactory()
                , new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }
    
    /**
     * 获取线程池实例
     * @return ExecutorService 线程池实例
     */
    public static ThreadPoolExecutor getInstance() {
        return THREAD_POOL;
    }
    
    /**
     * 动态设置核心线程数
     * @param corePoolSize 新的核心线程数
     */
    public static void setCorePoolSize(int corePoolSize) {
        if (THREAD_POOL != null) {
            THREAD_POOL.setCorePoolSize(corePoolSize);
        }
    }
    
    /**
     * 获取当前核心线程数
     * @return 当前核心线程数
     */
    public static int getCorePoolSize() {
        return THREAD_POOL != null ? THREAD_POOL.getCorePoolSize() : 0;
    }
    
    /**
     * 获取最大线程
     */
    public static int getMaximumPoolSize() {
        return THREAD_POOL != null ? THREAD_POOL.getMaximumPoolSize() : 0;
    }
    
    /**
     * 设置最大线程数
     * @param maximumPoolSize 新的最大线程数
     */
    public static void setMaximumPoolSize(int maximumPoolSize) {
        if (THREAD_POOL != null) {
            THREAD_POOL.setMaximumPoolSize(maximumPoolSize);
        }
    }
    
    /**
     * 获取当前活动线程数
     * @return 当前活动线程数
     */
    public static int getActiveCount() {
        return THREAD_POOL != null ? THREAD_POOL.getActiveCount() : 0;
    }
    
    /**
     * 获取线程池大小
     * @return 线程池大小
     */
    public static int getPoolSize() {
        return THREAD_POOL != null ? THREAD_POOL.getPoolSize() : 0;
    }
    
    /**
     * 关闭线程池
     */
    public static void shutdown() {
        if (THREAD_POOL != null) {
            THREAD_POOL.shutdown();
        }
    }
    
    /**
     * 立即关闭线程池
     */
    public static void shutdownNow() {
        if (THREAD_POOL != null) {
            THREAD_POOL.shutdownNow();
        }
    }
}
